import { reactive } from "vue";
import type { Options, State } from "./typing";
import type { PaginationProps } from "ant-design-vue";
import type { PageResult, ResponseBody } from "@/api/typing";
import { useI18n } from "vue-i18n";

export const useFetchPage = <T extends ResponseBody<PageResult<any>>>(
  queryData: (...args: any[]) => Promise<T>,
  options: Options<T["result"]["rows"]> = {}
) => {
  const {
    pageSize = 10,
    autoFetch = true,
    coverData,
    params = {},
    simple = false,
  } = options;
  const { t } = useI18n();
  const state = reactive<State<T["result"]["rows"]>>({
    loading: false,
    dataSource: [],
    pagination: {
      current: 1,
      simple,
      pageSize,
      total: 0,
      hideOnSinglePage: true, // 仅有一页时隐藏分页器
      showQuickJumper: true, // 展示跳转某页
      size: "small",
      showSizeChanger: true,
      showTotal: (total) => `${t("A total of")}${total}${t("articles")}`,
    },
  });
  /**查询数据 */
  const query = async () => {
    state.loading = true;
    const { success, result } = await queryData({
      page: state.pagination.current,
      pageSize: state.pagination.pageSize,
      ...params,
    });
    state.loading = false;
    if (success) {
      state.pagination.total = result.total;
      if (coverData) {
        state.dataSource = coverData(result.rows) as any[];
      } else {
        state.dataSource = result.rows;
      }
    }
  };
  /**重新加载 */
  const reload = async () => {
    state.pagination.current = 1;
    await query();
  };
  /**分页切换 */
  const handleChange = (p: PaginationProps) => {
    Object.assign(state.pagination, p);
    query();
  };
  if (autoFetch) {
    reload();
  }
  return {
    state,
    reload,
    handleChange,
  };
};
